package com.ppm.project.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ppm.common.constant.ErrorConstants;
import com.ppm.common.exception.CustomException;
import com.ppm.common.exception.user.ArticleIdUniqueCheckException;
import com.ppm.common.utils.DateUtils;
import com.ppm.common.utils.StringUtils;
import com.ppm.framework.manager.AsyncManager;
import com.ppm.framework.manager.factory.AsyncFactory;
import com.ppm.project.api.domain.Manuscripts;
import com.ppm.project.api.mapper.ManuscriptsMapper;
import com.ppm.project.api.service.IManuscriptsService;
import com.ppm.project.manuscripts.domain.PpmSiteSource;
import com.ppm.project.manuscripts.mapper.PpmSiteSourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 省平台共享文稿库Service业务层处理
 *
 * @author ppm
 * @date 2020-04-01
 */

@Service
public class ManuscriptsServiceImpl extends ServiceImpl<ManuscriptsMapper,Manuscripts> implements IManuscriptsService
{
    @Autowired
    private ManuscriptsMapper manuscriptsMapper;

    @Autowired
    private PpmSiteSourceMapper ppmSiteSourceMapper;


    /**
     * 查询省平台共享文稿库
     *
     * @param id 省平台共享文稿库ID
     * @return 省平台共享文稿库
     */
    @Override
    public Manuscripts selectManuscriptsById(Long id)
    {
        return manuscriptsMapper.selectManuscriptsById(id);
    }

    /**
     * 查询省平台共享文稿库列表
     *
     * @param manuscripts 省平台共享文稿库
     * @return 省平台共享文稿库
     */
    @Override
    public List<Manuscripts> selectManuscriptsList(Manuscripts manuscripts)
    {
        return manuscriptsMapper.selectManuscriptsList(manuscripts);
    }

    /**
     * 新增省平台共享文稿库
     *
     * @param manuscripts 省平台共享文稿库
     * @return 结果
     */
    @Override
    public int insertManuscripts(Manuscripts manuscripts)
    {

//        List<PpmSiteSource> sourceList = ppmSiteSourceMapper.selectList(new EntityWrapper<PpmSiteSource>()
//                .eq("site_code", manuscripts.getSourceFrom()));
//
//        if(sourceList!=null && sourceList.size() >0){
//            PpmSiteSource ppmSiteSource = sourceList.get(0);
//            if(StringUtils.isNotEmpty(sourceList.get(0).getSiteUrl())){
//
//                manuscripts.setH5Html(ppmSiteSource.getSiteUrl()+manuscripts.getH5Html());//拼接h5地址
//            }
//            Long orgIntegral = ppmSiteSource.getIntegral();
//
//            int updateRow = ppmSiteSourceMapper.updateForSet(" integral = integral + 1 and update_time = '"+DateUtils.getDate() +"' ",
//                    new EntityWrapper<PpmSiteSource>()//增加积分
//                    .eq("id", ppmSiteSource.getId())
//                    .eq("integral", orgIntegral));
//            if (updateRow <1){
//                throw new CustomException("操作失败,文章["+manuscripts.getArticleId()+"]在省平台增加积分异常,存在并发操作",ErrorConstants.CONCURRENT_ERROR);
//            }
//        }
//        int result = 0;
//        try {
//
//        }catch (Throwable e){
//            if(e instanceof DuplicateKeyException){
//
//                throw new DbUniqueCheckException(ErrorConstants.DB_UNIQUEKEY_CHECK_ERROR,"操作失败,文章["+manuscripts.getArticleId()+"]在省平台文稿库中已存在,不可重复共享",e);
//            }else{
//
//                throw new CustomException(e.getMessage());
//            }
//
//        }

        return manuscriptsMapper.insertManuscripts(manuscripts);
    }

    /**
     * 批量新增省平台共享文稿库
     *
     * @param manuscriptsList
     * @return
     */
    @Transactional
    @Override
    public boolean batchInsertManuscripts(List<Manuscripts> manuscriptsList) {
        boolean result = false;
        if(manuscriptsList !=null && manuscriptsList.size() >0){
            //articleId=站点code+文章id
            manuscriptsList.stream().forEach(
                    manuscripts -> {
                        manuscripts.setArticleId(
                                manuscripts.getArticleId()==null?"":
                                        manuscripts.getArticleId().contains("-")?manuscripts.getArticleId():
                                                manuscripts.getSourceFrom()+"-"+manuscripts.getArticleId());});
            Set<String> articleIds = manuscriptsList.stream().map(Manuscripts::getArticleId).collect(Collectors.toSet());
            //查询已存在的文章
            List<String> existArticleIds = manuscriptsMapper.selectExistArticleId(articleIds);
            List<String> notExistSiteCodes = null;
            List<Manuscripts> notExistList =null;
            if(existArticleIds != null && existArticleIds.size() > 0){
                //过滤已存在的文章,只更新信息不增加积分
                notExistList = manuscriptsList.stream().filter(manuscripts -> {
                    return !existArticleIds.contains(manuscripts.getArticleId()); }).collect(Collectors.toList());
                notExistSiteCodes = notExistList.stream().map(Manuscripts::getSourceFrom).collect(Collectors.toList());
            }else{
                notExistSiteCodes = manuscriptsList.stream().map(Manuscripts::getSourceFrom).collect(Collectors.toList());
            }
            if(notExistSiteCodes != null && notExistSiteCodes.size()>0){
                Map<String, Long> siteCodeCountMap = notExistSiteCodes.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
                PpmSiteSource ppmSiteSource = new PpmSiteSource();
                for(String sitecode : siteCodeCountMap.keySet()){

                    ppmSiteSource.setIntegral(siteCodeCountMap.get(sitecode));
                    ppmSiteSource.setUpdateTime(DateUtils.getNowDate());
                    ppmSiteSource.setSiteCode(sitecode);
                    if(ppmSiteSource.getIntegral() > 0){

                        ppmSiteSourceMapper.updateIntegral(ppmSiteSource);
                    }
                }
            }
            try {
                //批量新增或更新
                result = this.saveOrUpdateBatch(manuscriptsList);
                //异步解析H5中的资源文件
                PpmSiteSource siteSource = ppmSiteSourceMapper.
                        selectOne(new QueryWrapper<PpmSiteSource>().eq("site_code", manuscriptsList.get(0).getSourceFrom()));
                AsyncManager.me().execute(AsyncFactory.recordH5Source(manuscriptsList, siteSource.getSiteUrl()));
            }catch (Throwable e){

                if(e.getCause()!=null && StringUtils.isNotEmpty(e.getCause().getMessage()) && e.getCause().getMessage().contains("article_id_uq")){

                    throw new ArticleIdUniqueCheckException(ErrorConstants.DB_UNIQUEKEY_CHECK_ERROR,"操作失败,当前共享文稿在省平台文稿库已存在,不可重复共享",e);
                }else{

                    throw new CustomException(e.getMessage());
                }
            }
        }

        return result;
    }



    /**
     * 修改省平台共享文稿库
     *
     * @param manuscripts 省平台共享文稿库
     * @return 结果
     */
    @Override
    public int updateManuscripts(Manuscripts manuscripts)
    {
        return manuscriptsMapper.updateManuscripts(manuscripts);
    }

    /**
     * 批量删除省平台共享文稿库
     *
     * @param ids 需要删除的省平台共享文稿库ID
     * @return 结果
     */
    @Override
    public int deleteManuscriptsByIds(List<String> ids)
    {
        return manuscriptsMapper.deleteManuscriptsByIds(ids);
    }

    /**
     * 删除省平台共享文稿库信息
     *
     * @param id 省平台共享文稿库ID
     * @return 结果
     */
    @Override
    public int deleteManuscriptsById(Long id)
    {
        return manuscriptsMapper.deleteManuscriptsById(id);
    }
}
